<template>
  <div class="login">
    <!-- 导航栏 -->
    <van-nav-bar title="登录" />
    <!-- 表单部分 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        name="mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="rules.mobile"
      />
      <!-- 校验规则 -->
      <van-field
        v-model="code"
        name="code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="rules.code"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          :loading="loading"
          loading-text="加载中..."
          type="info"
          native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginApi } from "@/api";
import { setToken } from "@/utils/auth.js"
export default {
  data() {
    return {
      mobile: "13911111111",
      code: "246810",
      loading: false,
      rules: {
        mobile: [
          { required: true, message: "请输入手机号", trigger: "onBlur" },
          {
            pattern:
              /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
            message: "请输入正确的手机号",
            trigger: "onBlur",
          },
        ],
        code: [
          { required: true, message: "请输入验证码", trigger: "onBlur" },
          {
            pattern: /^\d{6}$/,
            message: "验证码长度为6",
            trigger: "onBlur",
          },
        ],
      },
    };
  },
  methods: {
    async onSubmit(data) {
      this.loading = true
      // console.log('怒号');
      // console.log(data);
      try {
        const res = await loginApi(data)
        // console.log(res);

        this.$store.commit("setToken", res.data.data)
        this.$toast.success("登录成功");
        //得到路径中的参数
        const url = this.$route.query.url
        //如果url存在
        if(url) {
          //跳转到url对应的地址
          this.$router.push(url)
        } else {
          this.$router.push('/layout/home')
        }
        
      } catch {
          this.$toast.fail("登录失败");
      } finally {
          this.loading = false
      }
     
        // .then((res) => {
        //   // console.log(res);
        //   this.$toast.success("登录成功");
        // })
        // .catch((error) => {
        //   // console.log(error);
        //   this.$toast.fail("登录失败");
        // })
        // .finally(() => {
        //   this.loading = false
        // })
    },
  },
};
</script>

<style lang="less">
</style>